package com.gionee.survey.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.gionee.survey.bean.Answer;
import com.gionee.survey.bean.Question;
import com.gionee.survey.bean.Survey;
import com.gionee.survey.service.IAnswerService;
import com.gionee.survey.service.IQuestionService;
import com.gionee.survey.service.ISurveyService;
import com.gionee.zxing.utils.QRCodeUtil;

/**
 * 问卷控制类
 * @author yuwei
 * @time 2017年4月13日 下午6:07:05
 */
@Controller
@RequestMapping("survey")
public class SurveyController {
	@Resource
	private ISurveyService surveyService;
	@Resource
	private IQuestionService questionService;
	@Resource
	private IAnswerService answerService;
	
	@RequestMapping("querySurvey")
	public String querySurvey(HttpServletRequest request, String id, String type){
		// 获取session 
		HttpSession session = request.getSession();
		// 获取问卷
		Survey survey = surveyService.selectByPrimaryKey(id);
		session.setAttribute("survey", survey);
		// 获取题目
		List<Question> questions = questionService.selectBySurveyId(id);
		session.setAttribute("questions", questions);
		// 获取答案
		List<Answer> answers = new ArrayList<Answer>();
		for (Question question : questions) {
			answers.addAll(answerService.selectByQuestionId(question.getId()));
		}
		session.setAttribute("answers", answers);
		if (type != null && "preview".equals(type)) {
			return "redirect:/preview.jsp";
		} else if (type != null && "mobile".equals(type)){
			return "redirect:/mobile.jsp";
		} else {
			return "redirect:/survey.jsp";
		}
	}
	
	@SuppressWarnings("deprecation")
	@RequestMapping("showQRCode")
	public String showQRCode(HttpServletResponse response, HttpServletRequest request, String id) throws Exception{
		StringBuffer uri = request.getRequestURL();
		String root = request.getRealPath("/");
		String logo = root + "/img/qr/logo/logo.jpg";
		String pic = root + "img/qr/";
		// 生成二维码
		String file = QRCodeUtil.encode(uri.toString().replace("showQRCode", "querySurvey") + "?id=" + id + "&type=mobile" , logo, pic, true);
		String str = JSON.parse("{'success':'img/qr/" + file + "'}").toString();
		response.getWriter().print(str);
		response.getWriter().flush();
		response.getWriter().close();
		return "success";
	}
}
